package com.runen.infinitemovement.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.ColumnActivityNameAdapter;
import com.runen.infinitemovement.adapter.FireRankingAdapter;
import com.runen.infinitemovement.adapter.HeardPictureAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.fragment.ChatFragment;
import com.runen.infinitemovement.fragment.CollageInfoFragment;
import com.runen.infinitemovement.model.api.ChallengeAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.CompanyHozomRankEntity;
import com.runen.infinitemovement.model.entity.PathPathSectionListEntity;
import com.runen.infinitemovement.model.entity.PathSectionListEntity;
import com.runen.infinitemovement.model.entity.PolyLineEntity;
import com.runen.infinitemovement.model.entity.RankDtoListEntity;
import com.runen.infinitemovement.model.entity.RideRoteJsonEntity;
import com.runen.infinitemovement.model.entity.SaveLongDataEntity;
import com.runen.infinitemovement.model.entity.WeLongMarchHomeEntity;
import com.runen.infinitemovement.model.enums.ActivityCompat;
import com.runen.infinitemovement.model.enums.SPCompat;
import com.runen.infinitemovement.tool.AnimationUtils;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.MapUtils;
import com.runen.infinitemovement.tool.notchtool.NotchTools;
import com.runen.infinitemovement.tool.notchtool.core.NotchProperty;
import com.runen.infinitemovement.tool.notchtool.core.OnNotchCallBack;
import com.runen.infinitemovement.widget.IndicatorSeekBar;
import com.runen.infinitemovement.widget.MapContainer;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.infinitemovement.widget.popupwind.HozomPoppupWindow;
import com.runen.infinitemovement.widget.popupwind.RoadIntroductionPoppupWindow;
import com.runen.infinitemovement.widget.popupwind.SharePoppupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.JsonUtils;
import com.runen.rxnetlibrary.utils.SharePreferenceUtils;
import com.runen.rxnetlibrary.utils.TimeUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WeTheLongMarchRoadActivity extends BaseActivity {

    @BindView(R.id.mapView)
    TextureMapView mapView;
    @BindView(R.id.tv_fire_num)
    TextView tvFireNum;
    @BindView(R.id.tv_contribute_fire)
    TextView tvContributeFire;
    @BindView(R.id.iv_certificate)
    ImageView ivCertificate;
    @BindView(R.id.iv_rule_introduce)
    ImageView ivRuleIntroduce;
    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.top_btn_right)
    Button topBtnRight;
    @BindView(R.id.rv_user_header)
    RecyclerView rvUserHeader;
    @BindView(R.id.tv_user_num)
    TextView tvUserNum;
    @BindView(R.id.tv_gs)
    TextView tvGs;
    @BindView(R.id.tv_company_progress)
    TextView tvCompanyProgress;
    @BindView(R.id.tv_sysj)
    TextView tvSysj;
    @BindView(R.id.tv_residue)
    TextView tvResidue;
    @BindView(R.id.indicator_seek_bar)
    IndicatorSeekBar indicatorSeekBar;
    @BindView(R.id.tv_yihuode)
    TextView tvYihuode;
    @BindView(R.id.tv_hozom_num)
    TextView tvHozomNum;
    @BindView(R.id.tv_target)
    TextView tvTarget;
    @BindView(R.id.tv_target_num)
    TextView tvTargetNum;
    @BindView(R.id.rl_top)
    RelativeLayout rlTop;
    @BindView(R.id.tv_pm)
    TextView tvPm;
    @BindView(R.id.tv_yh)
    TextView tvYh;
    @BindView(R.id.tv_fire)
    TextView tvFire;
    @BindView(R.id.rv_fire_ranking)
    RecyclerView rvFireRanking;
    @BindView(R.id.tv_check_more)
    TextView tvCheckMore;
    @BindView(R.id.rv_title2)
    RecyclerView rvTitle2;
    @BindView(R.id.fl_main)
    FrameLayout flMain;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.map_container)
    MapContainer mapContainer;
    @BindView(R.id.ll_hozom_finish)
    LinearLayout llHozomFinish;
    @BindView(R.id.tv_hozom_sum)
    TextView tvHozomSum;
    @BindView(R.id.iv_month_contribute)
    ImageView ivMonthContribute;

    private String logo;
    private WeLongMarchHomeEntity.DataBean dataBean;
    private boolean isOpen;
    private HeardPictureAdapter heardPictureAdapter;
    private FireRankingAdapter fireRankingAdapter;

    private String[] typeNames2 = new String[]{"讨论", "长征学院"};
    private ColumnActivityNameAdapter sportsTypeNameAdapter2;
    private List<String> typeList2 = new ArrayList<>();

    private List<PolyLineEntity> polyLineEntityList;
    private PolyLineEntity polyLineEntity;
    private double completionRate;// 当前进度

    private String companyName;
    private boolean isJumpToIntroduce = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_we_the_long_march_road;
    }

    private AMap aMap;
    private Polyline redPolyline;
    private Polyline polyline;
    private List<PathSectionListEntity> pathSectionListEntityList;
    private int point = 1;
    private String companyId;

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        //适配刘海屏
        NotchTools.getFullScreenTools().translucentStatusBar(this, new OnNotchCallBack() {
            @Override
            public void onNotchPropertyCallback(NotchProperty notchProperty) {
                llTitle.setPadding(0, CommonUtil.getStatusBarHeight(WeTheLongMarchRoadActivity.this), 0, 0);
                int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                llTitle.measure(w, h);
                rlTop.setPadding(0, llTitle.getMeasuredHeight(), 0, 0);
            }
        });
        boolean first = SharePreferenceUtils.getBoolean(this, SPCompat.FIRST_START_WE_LONG_ROAD, true);
        if (first) {
            isJumpToIntroduce = true;
            Intent intent = new Intent(this, IntroduceWeLoadActivity.class);
            startActivity(intent);
        }

        indicatorSeekBar.setEnabled(false);
        companyId = getIntent().getStringExtra("companyId");
        polyLineEntityList = new ArrayList<>();
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        MapUtils.setCustomMap(this, aMap);
        mapContainer.setScrollView(scrollView);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.getUiSettings().setLogoBottomMargin(-200);
        initViews();
        initSlidingDrawer();
//        initSportsTypeName();
        aMap.setOnPolylineClickListener(new AMap.OnPolylineClickListener() {
            @Override
            public void onPolylineClick(Polyline polyline) {
                List<LatLng> latLngs = polyline.getPoints();
                if (null != polyLineEntityList && polyLineEntityList.size() > 0) {
                    for (int i = 0; i < polyLineEntityList.size(); i++) {
                        if (polyLineEntityList.get(i).latLngs != null && polyLineEntityList.get(i).latLngs.size() > 0) {
                            if (latLngs != null && latLngs.size() > 0) {
                                if (latLngs.get(0).latitude == polyLineEntityList.get(i).latLngs.get(0).latitude) {
                                    if (null != pathSectionListEntityList && pathSectionListEntityList.size() > 0) {
                                        for (int j = 0; j < pathSectionListEntityList.size(); j++) {
                                            if (pathSectionListEntityList.get(j).sectionId.equals(polyLineEntityList.get(i).sectionId)) {
                                                showPopup(pathSectionListEntityList.get(j));
                                                break;
                                            }
                                        }
                                    }

                                    break;
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    boolean isFirst;

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (!isFirst) {
            initData();
            isFirst = true;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (dataBean != null && isJumpToIntroduce) {
            isJumpToIntroduce = false;
            if (aMap != null)
                aMap.clear();
            setView(dataBean);
        }
    }

    /**
     * 排行榜信息
     */
    private void initProgress() {
        String string = "?limit=100&page=1&type=2";
        new ChallengeAPI().getCompanyRank(string, new BaseResultCallback<CompanyHozomRankEntity>() {
            @Override
            public void onResponse(CompanyHozomRankEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        List<RankDtoListEntity> rankDtoListEntities = new ArrayList<>();
                        RankDtoListEntity rankDtoListEntity = new RankDtoListEntity();
                        rankDtoListEntity.name = response.data.name;
                        rankDtoListEntity.companyId = response.data.companyId;
                        rankDtoListEntity.headImage = response.data.headImage;
                        rankDtoListEntity.count = response.data.count;
                        rankDtoListEntity.isLowerStratum = response.data.isLowerStratum;
                        rankDtoListEntity.rank = response.data.rank;
                        rankDtoListEntity.logo = response.data.logo;
                        rankDtoListEntity.sportNumber = response.data.sportNumber;
                        rankDtoListEntity.tinderCount = response.data.tinderCount;
                        rankDtoListEntity.userId = response.data.userId;
                        rankDtoListEntity.robotStatus = response.data.robotStatus;
                        rankDtoListEntities.add(rankDtoListEntity);
                        tvUserNum.setText(String.format(enterNum, response.data.rankDtoList.size()));
                        if (response.data.rankDtoList != null && response.data.rankDtoList.size() > 0) {
                            rankDtoListEntities.addAll(response.data.rankDtoList);
                        }
                        fireRankingAdapter.setNewData(rankDtoListEntities);
                    }
                } else {
                    ToastUtils.showShort(response.msg);
                }

            }
        });
    }

    private void showPopup(PathSectionListEntity pathSectionListEntity) {
        RoadIntroductionPoppupWindow poppupWindow = RoadIntroductionPoppupWindow.getInstance(this, pathSectionListEntity);
        poppupWindow.show();
    }


    private void initViews() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.HORIZONTAL);
        rvUserHeader.setLayoutManager(layoutManager);
        heardPictureAdapter = new HeardPictureAdapter(this);
        rvUserHeader.setAdapter(heardPictureAdapter);

        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY < 70) {
                    llTitle.setBackground(null);
                } else {
                    llTitle.setBackground(CommonUtil.getDrawable(R.drawable.bg_title));
                }
            }
        });
    }

    private void initData() {
        showDialog();
        new ChallengeAPI().onWeLongMarchHome(new BaseResultCallback<WeLongMarchHomeEntity>() {
            @Override
            public void onResponse(WeLongMarchHomeEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (response.data != null) {
                        dataBean = response.data;
                        setView(response.data);
                    }
                } else {
                    ToastUtils.showShort(response.msg);
                }
            }
        });
    }


    private double lastDistance;
    private String checkId;
    private int gainedTinder;
    private String enterNum = "共有%s支队伍";

    @SuppressLint("NewApi")
    private void setView(WeLongMarchHomeEntity.DataBean data) {
        logo = data.logo;

        completionRate = data.completionRate;
        List<String> headerUrl = new ArrayList<>();
        if (data.participantHeadImages != null && data.participantHeadImages.size() > 0) {
            for (int i = 0; i < data.participantHeadImages.size(); i++) {
                if (i < 10) {
                    headerUrl.add(data.participantHeadImages.get(i));
                }
            }
            heardPictureAdapter.setNewData(headerUrl);
        }
        tvCompanyProgress.setText(String.valueOf(CommonUtil.Double2position(data.completionRate * 100)));
        indicatorSeekBar.setDoubleProgress(data.completionRate * 100);
        indicatorSeekBar.setProgress((int) (data.completionRate * 100));
        initProgress();
        /**
         * 活动剩余时间倒计时
         */
        if (null != data.activeDeadlineTime) {
            long now = System.currentTimeMillis();
            long endTime = TimeUtil.getDateTimeToLong(TimeUtil.dealDateFormat1(data.activeDeadlineTime));
            if (endTime > now) {
                lastTime = endTime;
                handler.sendEmptyMessage(1);
            } else if (endTime < now) {
                tvResidue.setText("活动已结束");
            }
        }
        tvTargetNum.setText(String.valueOf(data.tinderTarget));
        tvHozomNum.setText(String.valueOf(data.gainedTinder));
        tvFireNum.setText(String.valueOf(data.mySurplusTinder));
        gainedTinder = data.tinderTarget;
        if (fireRankingAdapter != null) {
            fireRankingAdapter.setTotalNum(gainedTinder);
            fireRankingAdapter.notifyDataSetChanged();
        }
        if (data.pathPathSectionList != null && data.pathPathSectionList.size() > 0) {
            pathSectionListEntityList = new ArrayList<>();
            for (int i = 0; i < data.pathPathSectionList.size(); i++) {
                PathPathSectionListEntity pathPathSectionList = data.pathPathSectionList.get(i);
                if (pathPathSectionList.pathSectionList != null && pathPathSectionList.pathSectionList.size() > 0) {
                    final double[] lastDistance = {0};
                    if (pathPathSectionList.companyLongMarchPath) {
                        checkId = pathPathSectionList.pathSectionList.get(0).sectionId;
                        lastDistance[0] = pathPathSectionList.mileage * completionRate;
                        pathSectionListEntityList.addAll(pathPathSectionList.pathSectionList);
                    }
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (int j = 0; j < pathPathSectionList.pathSectionList.size(); j++) {
                                try {
                                    PathSectionListEntity pathSectionListEntity = pathPathSectionList.pathSectionList.get(j);
                                    boolean isEndSection = false;
                                    if (pathPathSectionList.companyLongMarchPath) {
                                        isEndSection = j == pathPathSectionList.pathSectionList.size() - 1;
                                        Log.e("456456", "run: " + isEndSection);
                                    }
                                    setRideRoteQuery(pathSectionListEntity.translationFile, pathSectionListEntity.color,
                                            pathSectionListEntity.iconLink, pathSectionListEntity.iconLinkOver, pathSectionListEntity.icon,
                                            pathPathSectionList.companyLongMarchPath, pathSectionListEntity.sectionId,
                                            pathSectionListEntity.mileage, lastDistance[0], isEndSection);

                                    lastDistance[0] = lastDistance[0] - pathSectionListEntity.mileage;
                                    Thread.sleep(200);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }).start();

                }
            }
        }
    }

    private List<SaveLongDataEntity> saveLongDataEntities = new ArrayList<>();
    private SaveLongDataEntity saveLongDataEntity;

    public void setRideRoteQuery(String translationFile, String color, String iconLink, String iconLinkOver, String icon,
                                 boolean isOver, String sectionId, double mileage, double lastDistance, boolean isEndSection) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                new ChallengeAPI().getRideRoteQuery(translationFile, new BaseResultCallback<List<com.runen.infinitemovement.model.entity.RideRoteJsonEntity>>() {
                    @Override
                    public void onResponse(List<RideRoteJsonEntity> response) {
                        saveLongDataEntity = new SaveLongDataEntity();
                        saveLongDataEntity.color = color;
                        saveLongDataEntity.iconLink = iconLink;
                        saveLongDataEntity.iconLinkOver = iconLinkOver;
                        saveLongDataEntity.isOver = isOver;
                        saveLongDataEntity.mileage = mileage;
                        saveLongDataEntity.lastDistance = lastDistance;
                        saveLongDataEntity.roteJsonEntities = response;
                        saveLongDataEntity.sectionId = sectionId;
                        saveLongDataEntity.icon = icon;
                        saveLongDataEntity.isEndSection = isEndSection;
                        saveLongDataEntities.add(saveLongDataEntity);
                        Message message = new Message();
                        message.what = 2;
                        Bundle bundle = new Bundle();
                        bundle.putString("RideRote", JsonUtils.toJson(saveLongDataEntity));
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                });

            }
        }).start();
    }

    List<RideRoteJsonEntity> rideRoteJsonEntity;

    long lastTime;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    long now = lastTime - System.currentTimeMillis();
                    if (now > 0) {
                        tvResidue.setText(TimeUtil.formatSecond(now));
                        handler.sendEmptyMessageDelayed(1, 1000L);
                    } else {
                        handler.removeMessages(1);
                    }
                    break;
                case 2:
                    showDialog();
                    Bundle bundle = msg.getData();
                    String str = bundle.getString("RideRote");
                    SaveLongDataEntity saveLongDataEntity = JsonUtils.fromJson(str, SaveLongDataEntity.class);
                    if (saveLongDataEntity != null) {
                        pathPoint(saveLongDataEntity);
                    }
                    break;
                case 3:
                    AnimationUtils.showAndHiddenAnimation(llHozomFinish, AnimationUtils.AnimationState.STATE_HIDDEN, 500);
                    break;
            }
            return false;
        }
    });
    /**
     * 路线展示
     *
     * @param rideRoteJsonEntity
     * @param color
     * @param iconLink
     * @param iconLinkOver
     */
    private List<LatLng> latLngList = new ArrayList<>();
    private LatLngBounds.Builder newBounds = new LatLngBounds.Builder();
    private double fristLat;
    private double fristLon;

    private void pathPoint(SaveLongDataEntity saveLongDataEntity) {
        polyLineEntity = new PolyLineEntity();
        polyLineEntity.sectionId = saveLongDataEntity.sectionId;
        polyLineEntity.color = saveLongDataEntity.color;
        polyLineEntity.latLngs = new ArrayList<>();
        List<LatLng> latLngs = new ArrayList<>();
        rideRoteJsonEntity = saveLongDataEntity.roteJsonEntities;
        Log.e("456456", "pathPoint: " + saveLongDataEntity.isEndSection);
        for (int i = 0; i < rideRoteJsonEntity.size(); i++) {
            latLngList.add(new LatLng(rideRoteJsonEntity.get(i).latitude, rideRoteJsonEntity.get(i).longitude));
            latLngs.add(new LatLng(rideRoteJsonEntity.get(i).latitude, rideRoteJsonEntity.get(i).longitude));

            //最后一个点，标记图标为 延安会师
            Log.e("456456", "pathPoint1: " + saveLongDataEntity.isEndSection);
            if (saveLongDataEntity.isEndSection) {
                if (i == rideRoteJsonEntity.size() - 1)
                    setMarker4(rideRoteJsonEntity.get(i).latitude, rideRoteJsonEntity.get(i).longitude);
            }
        }
        List<LatLng> fullLatLngs = new ArrayList<>();//已经走过的路
        List<LatLng> xuLatLngs = new ArrayList<>();
        //当前路线是公司的路线
        if (saveLongDataEntity.isOver) {
            if (saveLongDataEntity.lastDistance >= 0) {
                if (saveLongDataEntity.lastDistance <= saveLongDataEntity.mileage) {
                    for (int i = 0; i < rideRoteJsonEntity.size(); i++) {
                        if (saveLongDataEntity.lastDistance < rideRoteJsonEntity.get(i).mileage) {
                            xuLatLngs.add(new LatLng(rideRoteJsonEntity.get(i).latitude, rideRoteJsonEntity.get(i).longitude));
                        } else {
                            /**
                             * 进度起点标记
                             */
                            if (fristLat == 0 && fristLon == 0) {
                                for (int j = 0; j < saveLongDataEntities.size(); j++) {
                                    if (checkId.equals(saveLongDataEntities.get(j).sectionId)) {
                                        fristLat = saveLongDataEntities.get(j).roteJsonEntities.get(0).latitude;
                                        fristLon = saveLongDataEntities.get(j).roteJsonEntities.get(0).longitude;
                                        setMarker3(fristLat, fristLon);
                                    }
                                }
                            }
                            fullLatLngs.add(new LatLng(rideRoteJsonEntity.get(i).latitude, rideRoteJsonEntity.get(i).longitude));
                        }
                    }
                    //未解锁图标
                    setMarker18dp(xuLatLngs.get(0).latitude, xuLatLngs.get(0).longitude, saveLongDataEntity.iconLink);
                    //已完成图标
                    setMarker(fullLatLngs.get(0).latitude, fullLatLngs.get(0).longitude, saveLongDataEntity.iconLinkOver);
                    setMarker2(fullLatLngs.get(fullLatLngs.size() - 1).latitude, fullLatLngs.get(fullLatLngs.size() - 1).longitude);
                    //走过的路画实线
                    polyline = aMap.addPolyline(new PolylineOptions().
                            addAll(fullLatLngs)
                            .width(20)
                            .setDottedLine(false) //打开虚线
                            .color(Color.parseColor(saveLongDataEntity.color)));
                    //整个路线画虚线
                    saveLongDataEntity.color = saveLongDataEntity.color.replace("#", "#4d");
                    polyline = aMap.addPolyline(new PolylineOptions().
                            addAll(latLngs)
                            .width(20)
                            .setDottedLine(true) //打开虚线
                            .color(Color.parseColor(saveLongDataEntity.color)));

                } else {
                    //无知
                    polyline = aMap.addPolyline(new PolylineOptions().
                            addAll(latLngs)
                            .width(20)
                            .setDottedLine(false) //打开虚线
                            .color(Color.parseColor(saveLongDataEntity.color)));
                }
            } else {
                //当前路线是公司路线，并且还未开始的路段显示虚线
                setMarker18dp(latLngs.get(0).latitude, latLngs.get(0).longitude, saveLongDataEntity.iconLink);
//                setMarker18dp(latLngs.get(latLngs.size() - 1).latitude,
//                        latLngs.get(latLngs.size() - 1).longitude, saveLongDataEntity.iconLink);
                saveLongDataEntity.color = saveLongDataEntity.color.replace("#", "#4d");
                polyline = aMap.addPolyline(new PolylineOptions().
                        addAll(latLngs)
                        .width(20)
                        .setDottedLine(true) //打开虚线
                        .color(Color.parseColor(saveLongDataEntity.color)));
            }
        } else {
            //当前路线不是公司的路线，显示实线
            if (latLngs.size() > 0) {
                setMarker7dp(latLngs.get(0).latitude, latLngs.get(0).longitude, saveLongDataEntity.icon);
                setMarker7dp(latLngs.get(latLngs.size() - 1).latitude, latLngs.get(latLngs.size() - 1).longitude, saveLongDataEntity.icon);
            }
            saveLongDataEntity.color = saveLongDataEntity.color.replace("#", "#4d");
            polyline = aMap.addPolyline(new PolylineOptions().
                    addAll(latLngs)
                    .width(10)
                    .setDottedLine(false) //打开虚线
                    .color(Color.parseColor(saveLongDataEntity.color)));
        }

        for (int j = 0; j < latLngList.size(); j++) {
            newBounds.include(new LatLng(latLngList.get(j).latitude, latLngList.get(j).longitude));
        }
        if (aMap != null) {
            aMap.animateCamera(CameraUpdateFactory.newLatLngBoundsRect(newBounds.build(),
                    CommonUtil.dp2px(this, 35),
                    CommonUtil.dp2px(this, 45),
                    CommonUtil.dp2px(this, 35),
                    CommonUtil.dp2px(this, 25)), null);
        }

        polyLineEntity.latLngs.addAll(latLngs);
        polyLineEntityList.add(polyLineEntity);
        dismissDialog();
    }

    /**
     * 小图标
     *
     * @param lat
     * @param lon
     * @param img
     */
    private void setMarker(double lat, double lon, String img) {
        View view = View.inflate(this, R.layout.view_custom_mark_small, null);
        ImageView iv_small = view.findViewById(R.id.iv_small);
        Glide.with(getApplicationContext()).load(img).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                iv_small.setImageDrawable(resource);
                Marker marker = aMap.addMarker(
                        new MarkerOptions()
                                .position(new LatLng(lat, lon))
                                .anchor(0.5f, 0.5f)
                                //添加markerID
                                .draggable(false).icon(BitmapDescriptorFactory.fromView(view)));
            }
        });
    }

    /**
     * 小图标
     *
     * @param lat
     * @param lon
     * @param img
     */
    private void setMarker18dp(double lat, double lon, String img) {
        View view = View.inflate(this, R.layout.view_custom_mark_small_18dp, null);
        ImageView iv_small = view.findViewById(R.id.iv_small);
        Glide.with(getApplicationContext()).load(img).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                iv_small.setImageDrawable(resource);
                Marker marker = aMap.addMarker(
                        new MarkerOptions()
                                .position(new LatLng(lat, lon))
                                .anchor(0.5f, 0.5f)
                                //添加markerID
                                .draggable(false).icon(BitmapDescriptorFactory.fromView(view)));
            }
        });
    }

    /**
     * 小图标
     *
     * @param lat
     * @param lon
     * @param img
     */
    private void setMarker7dp(double lat, double lon, String img) {
        View view = View.inflate(this, R.layout.view_custom_mark_small_7dp, null);
        ImageView iv_small = view.findViewById(R.id.iv_small);
        Glide.with(getApplicationContext()).load(img).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                iv_small.setImageDrawable(resource);
                Marker marker = aMap.addMarker(
                        new MarkerOptions()
                                .position(new LatLng(lat, lon))
                                .anchor(0.5f, 0.5f)
                                //添加markerID
                                .draggable(false).icon(BitmapDescriptorFactory.fromView(view)));
            }
        });
    }

    /**
     * 头像
     *
     * @param lat
     * @param lon
     * @param
     */
    private void setMarker2(double lat, double lon) {
        View view = View.inflate(this, R.layout.view_custom_mark, null);
        RoundedCornersImage rc_userHeader = view.findViewById(R.id.rc_userHeader);
        TextView tv_company_name = view.findViewById(R.id.tv_company_name);
        tv_company_name.setText("公司当前进度");
        Glide.with(getApplicationContext()).load(logo).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                rc_userHeader.setImageDrawable(resource);
                Marker marker = aMap.addMarker(
                        new MarkerOptions()
                                .position(new LatLng(lat, lon))
                                .anchor(0.5f, 0.5f)
                                //添加markerID
                                .draggable(false).icon(BitmapDescriptorFactory.fromView(view)));
            }
        });
    }

    /**
     * 开始标记旗帜
     *
     * @param lat
     * @param lon
     */
    private void setMarker3(double lat, double lon) {
        View view = View.inflate(this, R.layout.view_custom_mark_flag, null);
        Marker marker = aMap.addMarker(
                new MarkerOptions()
                        .position(new LatLng(lat, lon))
                        .anchor(0.5f, 0.7f)
                        //添加markerID
                        .draggable(false).icon(BitmapDescriptorFactory.fromView(view)));
    }

    /**
     * 结束标记延安会师
     *
     * @param lat
     * @param lon
     */
    private void setMarker4(double lat, double lon) {
        View view = View.inflate(this, R.layout.view_custom_mark_yanan, null);
        Marker marker1 = aMap.addMarker(
                new MarkerOptions()
                        .position(new LatLng(lat, lon))
                        .anchor(0.5f, 0.7f)
                        .title("yanan")
                        //添加markerID
                        .draggable(false).icon(BitmapDescriptorFactory.fromView(view)));
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.getTitle().equals("yanan")) {
                    Intent intent = new Intent(WeTheLongMarchRoadActivity.this, RoadLineDetailsActivity.class);
                    intent.putExtra("pathId", "1381895428991733761");
                    intent.putExtra(ActivityCompat.MAP_CLICK_YANAN, true);
                    startActivity(intent);
                }
                return true;
            }
        });
    }


    private void initSlidingDrawer() {

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        rvFireRanking.setLayoutManager(layoutManager1);
        fireRankingAdapter = new FireRankingAdapter(this);
        rvFireRanking.setAdapter(fireRankingAdapter);
        fireRankingAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (fireRankingAdapter.getData().get(position).robotStatus) return;
                Intent intent = new Intent(WeTheLongMarchRoadActivity.this, MyTeamActivity.class);
                intent.putExtra("targetId", fireRankingAdapter.getData().get(position).companyId);
                startActivity(intent);
            }
        });
    }

    private FragmentTransaction transaction;
    private ChatFragment chatFragment;
    private CollageInfoFragment collageInfoFragment;

    private void initSportsTypeName() {
        /**
         * 讨论和长征学院
         */
        LinearLayoutManager layoutManager1 = new GridLayoutManager(this, 2);
        rvTitle2.setLayoutManager(layoutManager1);
        sportsTypeNameAdapter2 = new ColumnActivityNameAdapter(this);
        rvTitle2.setAdapter(sportsTypeNameAdapter2);
        typeList2.clear();
        for (int i = 0; i < typeNames2.length; i++) {
            typeList2.add(typeNames2[i]);
        }
        sportsTypeNameAdapter2.setNewData(typeList2);
        sportsTypeNameAdapter2.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                sportsTypeNameAdapter2.setCheckPosition(position);
                sportsTypeNameAdapter2.notifyDataSetChanged();
                init(position);
            }
        });
        init(0);
    }

    private void init(int point) {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        transaction = supportFragmentManager.beginTransaction();
        hideFragment();
        switch (point) {
            case 0:
                if (chatFragment == null) {
                    chatFragment = new ChatFragment();
                    transaction.add(R.id.fl_main, chatFragment);
                }
                transaction.show(chatFragment);
                break;
            case 1:
                if (collageInfoFragment == null) {
                    collageInfoFragment = new CollageInfoFragment(1);
                    transaction.add(R.id.fl_main, collageInfoFragment);
                }
                transaction.show(collageInfoFragment);
                break;
        }
        transaction.commit();
    }

    private void hideFragment() {
        if (chatFragment != null) {
            //隐藏
            transaction.hide(chatFragment);
        }
        if (collageInfoFragment != null) {
            //隐藏
            transaction.hide(collageInfoFragment);
        }
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    @OnClick({R.id.tv_contribute_fire, R.id.iv_certificate, R.id.iv_rule_introduce,
            R.id.top_btn_left, R.id.top_btn_right, R.id.tv_check_more, R.id.iv_month_contribute, R.id.iv_knowledge_contest,
            R.id.ll_my_hz})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_contribute_fire:
                showHozom();
                break;
            case R.id.iv_certificate:
                startActivity(new Intent(this, MyCredentialActivity.class));
                break;
            case R.id.iv_rule_introduce:
                Intent intent1 = new Intent(this, WebActivity.class);
                intent1.putExtra("LINK_URL", Constant.RULE_INTRODUCE);
                startActivity(intent1);
                break;
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.top_btn_right:
                showShear();
                break;
            case R.id.tv_check_more:
                Intent intent = new Intent(this, RankingActivity.class);
                intent.putExtra("point", 2);
                startActivity(intent);
                break;
            case R.id.iv_month_contribute:
                Intent intent2 = new Intent(this, MonthContributeActivity.class);
                startActivity(intent2);
                break;
            case R.id.iv_knowledge_contest:
                Intent intent3 = new Intent(this, WebActivity.class);
                intent3.putExtra("LINK_URL", String.format(Constant.H5_ANSWER_REWARD, UserAPI.getUserToken()));
                startActivity(intent3);
                break;
            case R.id.ll_my_hz:
                Intent intent9 = new Intent(this, MyHozomActivity.class);
                startActivity(intent9);
                break;
        }
    }

    /**
     * 贡献火种
     */
    private void showHozom() {
        int num = Integer.parseInt(tvFireNum.getText().toString().trim());
        int hozomNum = Integer.parseInt(tvHozomNum.getText().toString().trim());
        HozomPoppupWindow hozomPoppupWindow = HozomPoppupWindow.getInstance(this);
        hozomPoppupWindow.show();
        hozomPoppupWindow.setOnHozonClickListener(new HozomPoppupWindow.OnHozonClickListener() {
            @Override
            public void onHozomClick(int number) {
                if (num < number) {
                    ToastUtils.showShort("火种数量不足" + number + "颗");
                } else {
                    JSONObject object = new JSONObject();
                    try {
                        object.put("tinder", number);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    showDialog();
                    new ChallengeAPI().onHozomTinder(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
                        @Override
                        public void onResponse(BaseResponseEntity<?> response) {
                            dismissDialog();
                            hozomPoppupWindow.dismiss();
                            if (response.getCode() == 0) {
                                int sum = num - number;
                                tvFireNum.setText(String.valueOf(sum));
                                tvHozomSum.setText(number + "颗");
                                tvHozomNum.setText(String.valueOf(hozomNum + number));
                                AnimationUtils.showAndHiddenAnimation(llHozomFinish, AnimationUtils.AnimationState.STATE_SHOW, 3000);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Thread.sleep(5000);
                                            handler.sendEmptyMessage(3);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }).start();

                            } else {
                                ToastUtils.showShort(response.getMessage());
                            }
                        }
                    });
                }
            }
        });
    }

    /**
     * 分享
     */
    private void showShear() {
        SharePoppupWindow.getInstance(this,
                "我正在挑战「重走长征路」来看看我的进度。",
                "体验不一样的长征路，与我一起挑战吧！",
                String.format(Constant.SHARE_WE_LONG, UserAPI.getUserId())).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

}
